package
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	
	import main.app.GameApp;
	import main.app.controller.HttpCenterManage;
	import main.app.model.http.HttpService;
	
	import starling.core.Starling;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.textures.Texture;
	import starling.utils.AssetManager;
	
	public class Root extends Sprite
	{
		//服务端的http地址字符串
		private var urlStr:String = "http://192.168.0.44/SpringMvc/hello.do";
		
		private static var sAssets:AssetManager;
		private static var _http:HttpService;
		
		public function Root()
		{
			_http = new HttpService(urlStr);
			
			initHttpEvent();
		}
		
		public function start(background:Texture, assets:AssetManager):void
		{
			sAssets = assets;
			var img:Image = new Image(background);
			addChild(img );
			
			/*var progressBar:ProgressBar = new ProgressBar(175, 20);
			progressBar.x = (background.width  - progressBar.width)  / 2;
			progressBar.y = (background.height - progressBar.height) / 2;
			progressBar.y = background.height * 0.85;
			addChild(progressBar);*/
			assets.loadQueue(function onProgress(ratio:Number):void
			{
				if (ratio == 1)
					Starling.juggler.delayCall(function():void
					{
						addChild(new GameApp());  //进入游戏界面
						removeChild(img);
					}, 0.15);
			});
		}
		
		private function initHttpEvent():void
		{
			//加载完成
			_http.addEventListener(Event.COMPLETE, urlLoaderCompleteHandler);
			//开始访问
			_http.addEventListener(Event.OPEN, urlLoaderOpenHandler);
			//加载进度
			_http.addEventListener(ProgressEvent.PROGRESS, urlLoaderProgressHandler);
			//跨域访问安全策略
			_http.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoaderSecurityErrorHandler);
			//Http状态事件
			_http.addEventListener(HTTPStatusEvent.HTTP_STATUS, urlLoaderHttpStatusHandler);    
			//访问出错事件
			_http.addEventListener(IOErrorEvent.IO_ERROR, urlLoaderIoErrorHandler);  
		}
		private function urlLoaderCompleteHandler(e:Event):void
		{      		
			var obj:Object =  com.adobe.serialization.json.JSON.decode(e.target.data);		
			HttpCenterManage.manage(obj);
		}
		
		private function urlLoaderOpenHandler(e:Event):void
		{
			trace(e);
		}
		
		private function urlLoaderProgressHandler(e:ProgressEvent):void
		{	
			trace(e);
		}
		
		private function urlLoaderSecurityErrorHandler(e:SecurityErrorEvent):void
		{
			trace(e);	
		}
		
		private function urlLoaderHttpStatusHandler(e:HTTPStatusEvent):void
		{
			trace(e);	
		}
		
		private function urlLoaderIoErrorHandler(e:IOErrorEvent):void
		{
			trace(e);	
		}
		public static function get assets():AssetManager
		{
			return sAssets; 
		}
		
		public static function get http():HttpService
		{
			return _http; 
		}
	}
}